<template>
  <div class="container">
    <div v-show="showDetail">
      <div class="weui_cells weui_cells_access" style="margin-top:0;">
        <a @click="selectCard" class="weui_cell" href="javascript:;">
          <div class="weui_cell_hd">
            <i class="fa fa-credit-card fa-2x icon-color" style="width:45px;margin-right:5px;display:block;"></i>
          </div>
          <div class="weui_cell_bd weui_cell_primary">
            <p>{{card?card.name:''}} <span style="margin-left:15px;" class="blue_tag">{{card?card.type:''}}</span></p>
            <p>{{card?card.num:''}}</p>
          </div>
          <div class="weui_cell_ft">
            选就诊卡
          </div>
        </a>
      </div>
      <div class="weui_cells_title" style="margin-top:5px;padding:0 5px;">{{ward?'送餐地址:':''}}{{ward}} {{bed}}{{bed?'床':''}}</div>
      <div v-show="!canDinner">
        <p style="padding:10px;" class="am-ft-sm am-ft-gray">
          <span class="am-ft-orange"><i class="fa fa-info-circle"></i></span> 支付宝订餐只有住院病人才能使用，目前支付宝订餐服务处于测试阶段，只针对一部分科室开放，如果打开点餐页面没有看到<span class="am-ft-orange">菜单</span>，说明您所在的科室还未开放支付宝订餐
        </p>
      </div>
      <div v-show="canDinner">
        <div class="am-tab" style="margin-top:5px;">
          <div v-for="day in days" @click="selectedDate=day.date" class="am-tab-item" :data-tab="day.date==selectedDate?'selected':''">{{day.day}}</div>
        </div>
        <div id="menu-scroll-wrapper" class="menu-scroll-wrapper">
          <div class="scroller">
            <ul>
              <li v-for="hmt in hmts" :class="{ 'menu-item-on': selectedHmt==(hmt.fpId+'-'+hmt.hmtId), 'menu-item-off': selectedHmt!=(hmt.fpId+'-'+hmt.hmtId) }">
                <a @click="selectedHmt=hmt.fpId+'-'+hmt.hmtId" href="javascript:;"><span>{{'['+hmt.fpName+'] '+hmt.hmtName}}</span></a>
              </li>
            </ul>
          </div>
        </div>
        <div id="list-scroll-wrapper" class="list-scroll-wrapper">
          <div class="scroller">
            <div class="weui_cells am-ft-sm" style="margin-top:-1px;">
              <div v-for="food in foods" class="weui_cell">
                <div class="weui_cell_hd">
                  <i class="fa fa-cutlery fa-2x icon-color" style="width:35px;margin-right:5px;display:block;"></i>
                </div>
                <div class="weui_cell_bd weui_cell_primary">
                  <p>{{food.foodName}}</p>
                  <p style="padding-top:5px;"><span class="am-ft-orange am-ft-lg">￥{{food.price}}</span>
                    <span style="display:inline-block;float:right;">
                  <a v-show="food.selectedCnt" @click="minusFood(food.foodId)" href="javascript:;"><i class="fa fa-minus-square-o fa-2x"></i></a>
                  <span class="am-ft-orange am-ft-xl" style="margin:0 3px;">{{food.selectedCnt==0?'':food.selectedCnt}}</span>
                    <a @click="plusFood(food.foodId)" href="javascript:;"><i class="fa fa-plus-square-o fa-2x"></i></a>
                    </span>
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div>
          <div class="weui_actionsheet weui_actionsheet_toggle">
            <div style="margin-top:0;border-top: 1px solid #d9d9d9;background-color:#fff;">
              <div style="padding: 10px 0; text-align: center;font-size: 18px;">
                <span @click="showActionSheet" style="display:inline-block;width:60%;text-align:left;">
                已选:<span class="am-ft-orange">{{selectedCntAndPrice.cnt}}</span>个,<span class="am-ft-orange">￥{{selectedCntAndPrice.price}}</span>
                </span>
                <span style="display:inline-block;width:36%;">
                <a v-on:click.stop.prevent="doDinner" href="javascript:;" style="display: inline-block;padding: 0 .75em;background-color: #04be02;text-align: center;
                text-decoration: none;color: #fff;-webkit-tap-highlight-color: rgba(0,0,0,0);">支付</a>
              </span>
              </div>
            </div>
          </div>
        </div>
        <div>
          <div v-el:mask class="weui_mask_transition"></div>
          <div v-el:actionsheet class="weui_actionsheet">
            <div style="max-height:306px;overflow-x:hidden;overflow-y:auto;">
              <div v-for="sf in selectedFoods">
                <div class="weui_cells_title">{{sf.categoryName}}</div>
                <div class="weui_cells">
                  <div v-for="isf in sf.foods" class="weui_cell">
                    <div class="weui_cell_bd weui_cell_primary" style="width:100%;">
                      <p class="am-ft-ellipsis" style="display:inline-block;width:50%;">
                        {{isf.foodName}}
                      </p>
                      <p style="display:inline-block;width:50%;float:right;">
                        <span class="am-ft-orange am-ft-lg" style="display:inline-block;margin:0px;width:70px;">￥{{isf.totalPrice}}</span>
                        <span style="margin:0 5px;">
                      <a @click="minusSelectedFood(sf.date,sf.fpId,sf.hmtId,isf.foodId)" href="javascript:;"><i class="fa fa-minus-square-o"></i></a>
                      <span class="am-ft-orange am-ft-xl" style="margin:0 3px;">{{isf.selectedCnt}}</span>
                        <a @click="plusSelectedFood(sf.date,sf.fpId,sf.hmtId,isf.foodId)" href="javascript:;"><i class="fa fa-plus-square-o"></i></a>
                        </span>
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div style="padding: 10px 0; text-align: center;font-size: 18px;background-color:#fff;margin-top:5px;">
              <span style="display:inline-block;width:50%;text-align:left;">
              已选:<span class="am-ft-orange">{{selectedCntAndPrice.cnt}}</span>个,<span class="am-ft-orange">￥{{selectedCntAndPrice.price}}</span>
              </span>
              <span style="display:inline-block;width:46%;">
              <a v-on:click.stop.prevent="doDinner" href="javascript:;" style="display: inline-block;padding: 0 .75em;background-color: #04be02;text-align: center;text-decoration: none;color: #fff;-webkit-tap-highlight-color: rgba(0,0,0,0);">支付</a>
              <a v-on:click.stop.prevent="clear" href="javascript:;" style="display: inline-block;padding: 0 .75em;border:1px #04be02 solid;text-align: center;text-decoration: none;color: #000;-webkit-tap-highlight-color: rgba(0,0,0,0);">清空</a>
            </span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="reg-success" v-show="showSuccess">
      <div class="weui_msg">
        <div class="weui_icon_area"><i class="weui_icon_success weui_icon_msg"></i></div>
        <div class="weui_text_area">
          <h2 class="weui_msg_title">点餐成功</h2>
          <p class="weui_msg_desc">{{succeedMsg}}</p>
        </div>
        <div class="weui_opr_area">
          <p class="weui_btn_area">
            <a href="javascript:;" @click="goOrderDetail" class="weui_btn weui_btn_primary">查看详情</a>
          </p>
        </div>
      </div>
    </div>
    <div class="reg-failed" v-show="showFailed">
      <div class="weui_msg">
        <div class="weui_icon_area"><i class="weui_icon_warn weui_icon_msg"></i></div>
        <div class="weui_text_area">
          <h2 class="weui_msg_title">点餐失败</h2>
          <p class="weui_msg_desc">{{failedMsg}}</p>
        </div>
        <div class="weui_opr_area">
          <p class="weui_btn_area">
            <a href="javascript:;" @click="gotoPortal" class="weui_btn weui_btn_primary">返回首页</a>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped>
.ft-sm p {
  padding: 3px;
  font-size: 12px;
}

.blue_tag {
  background-color: #0ae;
  color: #fff;
  font-size: 13px;
  padding: 2px 4px;
  border: none;
  vertical-align: middle;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  border-radius: 3px;
}

.orange_tag {
  background-color: #ff8208;
  color: #fff;
  font-size: 13px;
  padding: 2px 4px;
  border: none;
  vertical-align: middle;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  border-radius: 3px;
}

.weui_navbar_item {
  padding: 6px 0;
  color: #000;
}

.weui_bar_item_on {
  color: #FFF;
  background: #0ae;
}

.weui_tab_bd {
  padding-bottom: 34px;
}

.menu-scroll-wrapper {
  position: absolute;
  top: 150px;
  left: 0;
  width: 90px;
  bottom: 43px;
  overflow: hidden;
}

.menu-scroll-wrapper ul {
  width: 100%;
  position: relative;
}

.menu-scroll-wrapper ul:after {
  content: " ";
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 1px;
  border-top: 1px solid #c8c8cd;
  color: #c8c8cd;
  -webkit-transform-origin: 0 0;
  transform-origin: 0 0;
  -webkit-transform: scaleY(0.5);
  transform: scaleY(0.5);
}

.menu-scroll-wrapper li {
  position: relative;
}

.menu-scroll-wrapper li:before {
  content: " ";
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 1px;
  border-top: 1px solid #c8c8cd;
  color: #c8c8cd;
  -webkit-transform-origin: 0 0;
  transform-origin: 0 0;
  -webkit-transform: scaleY(0.5);
  transform: scaleY(0.5);
}

.menu-scroll-wrapper li a {
  display: block;
  margin: 0px 5px;
  padding: 8px 0 8px 3px;
  color: #515151;
  font-size: 13px;
}

.menu-item-on {
  background-color: white;
}

.menu-item-on p {
  padding-left: 3px;
  border-left: 2px #0ae solid;
}

.menu-item-off:after {
  content: " ";
  position: absolute;
  right: 0;
  top: 0;
  width: 1px;
  height: 100%;
  border-right: 1px solid #c8c8cd;
  color: #c8c8cd;
  -webkit-transform-origin: 0 0;
  transform-origin: 0 0;
  -webkit-transform: scaleX(0.5);
  transform: scaleX(0.5);
}

.list-scroll-wrapper {
  position: absolute;
  top: 150px;
  left: 90px;
  right: 0;
  bottom: 40px;
  overflow: hidden;
}

.scroller {
  position: absolute;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  width: 100%;
  -webkit-transform: translateZ(0);
  -moz-transform: translateZ(0);
  -ms-transform: translateZ(0);
  -o-transform: translateZ(0);
  transform: translateZ(0);
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-text-size-adjust: none;
  -moz-text-size-adjust: none;
  -ms-text-size-adjust: none;
  -o-text-size-adjust: none;
  text-size-adjust: none;
}
</style>
<script type="text/ecmascript-6">
import {
  showCommonToast,
  hideCommonToast,
  showLoadingToast,
  hideLoadingToast
} from '../../vuex/actions'
import { iScroll as IScroll } from '../../assets/lib/iscroll4/iscroll'
import _ from 'underscore'
import $ from 'jquery'

export default {
  name: 'DoDinnerView',
  data: function () {
    return {
      showDetail: true,
      showSuccess: false,
      showFailed: false,
      canDinner: false,
      selectedDate: '2016-05-24',
      selectedHmt: '',
      ward: '',
      bed: '',
      categories: [],
      selected: [],
      failedMsg: '',
      succeedMsg: '',
      billId: -1
    }
  },
  computed: {
    days: function () {
      return _.uniq(_.map(this.categories, function (val) {
        return {
          date: val.Date,
          day: val.Day
        }
      }), true, function (val) {
        return val.date
      })
    },
    hmts: function () {
      return _.map(_.where(this.categories, { Date: this.selectedDate }), function (val) {
        return {
          fpId: val.FpId,
          fpName: val.FpName,
          hmtId: val.HmtId,
          hmtName: val.HmtName
        }
      })
    },
    foods: function () {
      var selectedDate = this.selectedDate
      var selectedHmt = this.selectedHmt
      var category = _.find(this.categories, function (val) {
        return val.Date === selectedDate && (val.FpId + '-' + val.HmtId) === selectedHmt
      })
      if (!category) {
        return []
      }
      return _.map(category.Items, function (val) {
        return {
          foodId: val.FoodId,
          foodName: val.FoodName,
          price: val.Price,
          selectedCnt: val.SelectedCnt
        }
      })
    },
    selectedCntAndPrice: function () {
      var cnt = 0
      var price = 0
      var categories = this.categories
      for (var i = 0; i < categories.length; i++) {
        var category = categories[i]
        for (var j = 0; j < category.Items.length; j++) {
          var item = category.Items[j]
          if (item.SelectedCnt > 0) {
            cnt = cnt + item.SelectedCnt
            price = price + (item.SelectedCnt * item.Price)
          }
        }
      }
      price = Math.round(price * 100) / 100
      return {
        cnt,
        price
      }
    },
    selectedFoods: function () {
      var selectedFoods = []
      var categories = this.categories
      for (var i = 0; i < categories.length; i++) {
        var category = categories[i]
        for (var j = 0; j < category.Items.length; j++) {
          var item = category.Items[j]
          if (item.SelectedCnt > 0) {
            var selectedCategory = _.find(selectedFoods, function (val) {
              return val.categoryId === (category.Date + '-' + category.FpId + '-' + category.HmtId)
            })
            if (!selectedCategory) {
              selectedCategory = {
                categoryId: (category.Date + '-' + category.FpId + '-' + category.HmtId),
                categoryName: (category.Day + ' [' + category.FpName + ']' + category.HmtName),
                date: category.Date,
                fpId: category.FpId,
                hmtId: category.HmtId,
                foods: []
              }
              selectedFoods.push(selectedCategory)
            }
            selectedCategory.foods.push({
              foodId: item.FoodId,
              foodName: item.FoodName,
              selectedCnt: item.SelectedCnt,
              totalPrice: item.SelectedCnt * item.Price
            })
          }
        }
      }
      return selectedFoods
    }
  },
  vuex: {
    getters: {
      card: ({ card }) => _.findWhere(card.cards, { isSelected: true })
    },
    actions: {
      showCommonToast,
      hideCommonToast,
      showLoadingToast,
      hideLoadingToast
    }
  },
  methods: {
    selectCard: function () {
      this.$router.go({ name: 'selectCard' })
    },
    showActionSheet: function () {
      if (this.selectedCntAndPrice.price === 0) {
        return
      }
      var self = this
      var mask = $(this.$els.mask)
      var weuiActionsheet = $(this.$els.actionsheet)
      weuiActionsheet.addClass('weui_actionsheet_toggle')
      mask.show().addClass('weui_fade_toggle').one('click', function () {
        self.hideActionSheet(weuiActionsheet, mask)
      })
      $(this.$els.actionsheetcancel).one('click', function () {
        self.hideActionSheet(weuiActionsheet, mask)
      })
      weuiActionsheet.unbind('transitionend').unbind('webkitTransitionEnd')
    },
    hideActionSheet: function (weuiActionsheet, mask) {
      weuiActionsheet.removeClass('weui_actionsheet_toggle')
      mask.removeClass('weui_fade_toggle')
      weuiActionsheet.on('transitionend', function () {
        mask.hide()
      }).on('webkitTransitionEnd', function () {
        mask.hide()
      })
    },
    getFoodList: function () {
      if (!this.card || !this.card.id || this.card.id === -1) {
        return
      }

      var self = this
      this.$ajax.get('GetFoodList', 'Dinner', {
        cardId: this.card.id
      }).then(function (data) {
        if (data.ResultCode === '0') {
          self.canDinner = data.CanDinner
          self.ward = data.Ward
          self.bed = data.Bed
          self.categories = data.Categories
          if (self.categories.length <= 0) {
            self.canDinner = false
          } else {
            self.selectedDate = self.categories[0].Date
            self.selectedHmt = self.categories[0].FpId.toString() + '-' + self.categories[0].HmtId.toString()
          }
        }
      })
    },
    getFood: function (foodId) {
      var selectedDate = this.selectedDate
      var selectedHmt = this.selectedHmt
      var categories = this.categories
      var category = _.find(categories, function (val) {
        return val.Date === selectedDate && (val.FpId + '-' + val.HmtId) === selectedHmt
      })
      if (category) {
        var food = _.find(category.Items, function (val) {
          return val.FoodId === foodId
        })
        return food
      }

      return null
    },
    minusFood: function (foodId) {
      var food = this.getFood(foodId)
      if (food) {
        food.SelectedCnt = food.SelectedCnt - 1
        if (food.SelectedCnt < 0) {
          food.SelectedCnt = 0
        }
      }
    },
    plusFood: function (foodId) {
      var food = this.getFood(foodId)
      if (food) {
        food.SelectedCnt = food.SelectedCnt + 1
      }
    },
    minusSelectedFood: function (date, fpId, hmtId, foodId) {
      var categories = this.categories
      var category = _.find(categories, function (val) {
        return val.Date === date && val.FpId === fpId && val.HmtId === hmtId
      })
      if (category) {
        var food = _.find(category.Items, function (val) {
          return val.FoodId === foodId
        })
        if (food) {
          food.SelectedCnt = food.SelectedCnt - 1
          if (food.SelectedCnt < 0) {
            food.SelectedCnt = 0
          }
        }
      }
    },
    plusSelectedFood: function (date, fpId, hmtId, foodId) {
      var categories = this.categories
      var category = _.find(categories, function (val) {
        return val.Date === date && val.FpId === fpId && val.HmtId === hmtId
      })
      if (category) {
        var food = _.find(category.Items, function (val) {
          return val.FoodId === foodId
        })
        if (food) {
          food.SelectedCnt = food.SelectedCnt + 1
        }
      }
    },
    clear: function () {
      var categories = this.categories
      for (var i = 0; i < categories.length; i++) {
        var category = categories[i]
        for (var j = 0; j < category.Items.length; j++) {
          var item = category.Items[j]
          item.SelectedCnt = 0
        }
      }

      var mask = $(this.$els.mask)
      var weuiActionsheet = $(this.$els.actionsheet)
      this.hideActionSheet(weuiActionsheet, mask)
    },
    doDinner: function () {
      if (this.selectedCntAndPrice.price === 0) {
        this.showCommonToast({ msg: '请选择菜品' })
        return
      }

      var self = this

      this.showLoadingToast({ msg: '正在点餐...' }, false)

      this.$ajax.post('CreateDinnerOrder', 'Dinner', {}, {
        CardId: this.card.id,
        Orders: _.map(this.selectedFoods, function (val) {
          return {
            Date: val.date,
            FpId: val.fpId,
            HmtId: val.hmtId,
            Items: _.map(val.foods, function (item) {
              return {
                FoodId: item.foodId,
                Cnt: item.selectedCnt
              }
            })
          }
        })
      }, false).then(function (data) {
        if (data.ResultCode !== '0') {
          self.failedMsg = data.ResultMsg
          self.showDetail = false
          self.showSuccess = false
          self.showFailed = true
          self.hideLoadingToast()
        } else {
          self.billId = data.BillId
          self.callPay(data.PayString)
        }
      })
    },
    callPay: function (payString) {
      if (payString === '') {
        this.paySucceed()
        return
      }
      // 支付操作
      var form = $(payString)
      form.submit()
    },
    payFailed: function () {
      this.$ajax.get('PayFailed', 'Dinner', {
        billId: this.billId
      }, false).then(function (data) {

      })

      this.hideLoadingToast()

      this.showCommonToast({ msg: '您已取消支付' })
    },
    paySucceed: function () {
      var self = this
      this.$ajax.get('GetDinnerBillStatus', 'Dinner', {
        billId: this.billId
      }, false).then(function (data) {
        if (data.ResultCode !== '0') {
          self.hideLoadingToast()
        } else {
          if (data.DinnerStatus === '1') {
            self.failedMsg = data.FailedMsg
            self.showDetail = false
            self.showSuccess = false
            self.showFailed = true
            self.hideLoadingToast()
          } else if (data.DinnerStatus === '0') {
            self.showDetail = false
            self.showSuccess = true
            self.showFailed = false
            self.succeedMsg = data.SucceedMsg
            self.hideLoadingToast()
          } else {
            window.setTimeout(function () {
              self.paySucceed()
            }, 500)
          }
        }
      })
    },
    gotoPortal: function () {
      this.$router.replace({ name: 'portal' })
    },
    goOrderDetail: function () {
      this.$router.replace({ name: 'dinnerOrderList' })
    }
  },
  ready: function () {
    $('#footer').hide()
    this.listIScroll = new IScroll('list-scroll-wrapper', { hScroll: false, vScroll: true, hScrollbar: false, vScrollbar: false })
    this.menuIScroll = new IScroll('menu-scroll-wrapper', { hScroll: false, vScroll: true, hScrollbar: false, vScrollbar: false })

    this.$watch('selectedDate', function (val) {
      this.$nextTick(function () {
        this.listIScroll.refresh()
        this.listIScroll.scrollTo(0, 0, 0)
      })
    })

    this.$watch('selectedHmt', function (val) {
      this.$nextTick(function () {
        this.listIScroll.refresh()
        this.listIScroll.scrollTo(0, 0, 0)
      })
    })

    this.$watch('card', function (val) {
      this.getFoodList()
    })

    this.getFoodList()
  },
  beforeDestroy: function () {
    this.listIScroll.destroy()
    this.listIScroll = null

    this.menuIScroll.destroy()
    this.menuIScroll = null
    $('#footer').show()
  },
  listIScroll: null,
  menuIScroll: null
}
</script>
